package com.jackson.engineeringtechnologyguide.post;

/*
 * Author: JacksonCoder
 * FileName: CouponHandlerFactory
 * Version: 1.0.0
 * Date: 2025/1/11
 */

import com.jackson.engineeringtechnologyguide.post.couponhandler.CouponHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * coupon 处理器工厂类
 */
@Slf4j
@Component
public class CouponHandlerFactory implements BeanPostProcessor {

    private static final Map<CouponTypeEnum, CouponHandlerService> serviceMap = new ConcurrentHashMap<>();


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof CouponHandlerService) {
            // 获取对象运行时对象类
            Class<?> clazz = bean.getClass();
            //获取 自定义的注解
            CouponHandlerProcessor annotation = clazz.getAnnotation(CouponHandlerProcessor.class);
            // TODO  可以对 bean 进行校验
            // 绑定对饮关系
            serviceMap.put(annotation.value(), (CouponHandlerService) bean);

            log.info("...");
        }
        return bean;
    }

    /**
     * 根据优惠券类型获取处理器
     * @param type
     * @return
     */
    public CouponHandlerService getHandler(CouponTypeEnum type) {
        return serviceMap.get(type);
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
